package com.fancon.android.gardenjokesx.rpc;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import me.openphoto.android.app.net.ApiRequest;
import me.openphoto.android.app.net.ApiRequest.Parameter;
import me.openphoto.android.app.net.ApiResponse;
import me.openphoto.android.app.net.HttpEntityWithProgress;
import me.openphoto.android.app.net.HttpEntityWithProgress.ProgressListener;
import me.openphoto.android.app.net.UploadMetaData;
import me.openphoto.android.app.net.UploadResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.FacebookUser;
import com.fancon.android.gardenjokesx.entity.FlickrUser;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.Place;
import com.fancon.android.gardenjokesx.entity.TumblrUser;
import com.fancon.android.gardenjokesx.entity.TwitterUser;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.entity.WeiboUser;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.SocialUntil;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.rpc.ApiConnect;

/**
 * Api Connect class
 * 
 * @author DuyTX
 * 
 */
public class GardenJokesApiConnect extends ApiConnect {
	public GardenJokesApiConnect(Context context) {
		super(context);
		mContext = context;
	}

	public boolean isImageAttach() {
		return isImageAttach;
	}

	public void setImageAttach(boolean isImageAttach) {
		this.isImageAttach = isImageAttach;
	}

	/** Base API URL */
	public static final String BASE_API_URL = "http://www.xcomic.biz/lol/api/";
	/** API Group */
	public static final String GROUP_A = "Start";
	public static final String GROUP_F = "Follow";
	public static final String GROUP_L = "Login";
	public static final String GROUP_T = "Trend";
	public static final String GROUP_S = "SignUp";
	public static final String GROUP_U = "User";
	public static final String GROUP_M = "View";
	public static final String GROUP_P = "Photo";

	private Context mContext;
	public static final int NORMAL_TIMEOUT = 60000;
	public static final int POST_IMAGE_TIMEOUT = 90000;

	public UIHandler uiHandler;
	public static Boolean isShowingDialog = false;
	private boolean isImageAttach = Constant.OFF;

	private final class UIHandler extends Handler {
		public static final int DISPLAY_UI_TOAST = 0;
		public static final int DISPLAY_UI_DIALOG = 1;

		public UIHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UIHandler.DISPLAY_UI_TOAST: {

				Toast t = Toast.makeText(mContext, (String) msg.obj,
						Toast.LENGTH_LONG);
				t.show();
			}
			case UIHandler.DISPLAY_UI_DIALOG:
				showErrorDialog(msg);
			default:
				break;
			}
		}

		/**
		 * show error dialog when have error
		 * 
		 * @param msg
		 */
		public void showErrorDialog(Message msg) {
			try {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setMessage((String) msg.obj)
						.setCancelable(true)
						.setNegativeButton(
								mContext.getResources().getString(
										R.string.common_ok),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										isShowingDialog = false;
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.setCancelable(false);
				alert.show();
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
	}

	protected void handleUIRequest(String message) {
		Message msg = uiHandler.obtainMessage(UIHandler.DISPLAY_UI_DIALOG);
		msg.obj = message;
		uiHandler.sendMessage(msg);
	}

	/**
	 * Get api data by group and method If have wifi network or 3G => get from
	 * server No network => get from cache
	 * 
	 * @author binhbt
	 * @param context
	 * @param group
	 * @param method
	 * @param paramList
	 * @return
	 */
	public String getApiData(Context context, String group, String method,
			List<NameValuePair> paramList) {
		String url = buildBaseUrl(group, method);
		try {
			return getApiData(url, paramList);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Sua lai dung http client va dat timeout la 10s
	 * 
	 * @url: url cua request
	 */
	public String execGet(Context context, String url,
			List<NameValuePair> paramList) {
		if (null != paramList) {
			url += getStrParam(paramList);
		}
		HttpClient hClient = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(hClient.getParams(), 10000); // Timeout
		HttpConnectionParams.setSoTimeout(hClient.getParams(), NORMAL_TIMEOUT);
		try {
			Log.d("URL", "URL REQUEST : " + url);
			HttpGet hget = new HttpGet();
			hget.setURI(new URI(url));
			HttpResponse response = hClient.execute(hget);
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				String responseString = out.toString();
				Log.d("response", responseString);
				return responseString;
			} else {
				String mess = "";
				mess = mContext.getResources().getString(R.string.ERR0006);
				if (!isShowingDialog) {
					isShowingDialog = true;
					showMessage(mess);
				}
				return "";
			}
		} catch (ConnectTimeoutException e) {

			Log.e("ApiConnectexecGet", e.getMessage());
			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0007);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";

		} catch (Exception e) {

			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0006);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";

		}
	}

	/**
	 * Sua lai dung http client va dat timeout la 10s
	 */
	public String execGet(Context context, String group, String method,
			List<NameValuePair> paramList) {
		String url = BASE_API_URL + group + '/' + method;
		if (null != paramList) {
			url += getStrParam(paramList);
		}
		HttpClient hClient = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(hClient.getParams(), 10000); // Timeout
		HttpConnectionParams.setSoTimeout(hClient.getParams(), NORMAL_TIMEOUT);
		try {
			Log.d("URL", "URL REQUEST : " + url);
			HttpGet hget = new HttpGet();
			hget.setURI(new URI(url));
			HttpResponse response = hClient.execute(hget);
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				String responseString = out.toString();
				Log.d("response", responseString);
				return responseString;
			} else {
				String mess = "";
				mess = mContext.getResources().getString(R.string.ERR0006);
				if (!isShowingDialog) {
					isShowingDialog = true;
					showMessage(mess);
				}
				return "";
			}
		} catch (ConnectTimeoutException e) {

			Log.e("ApiConnectexecGet", e.getMessage());
			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0007);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";

		} catch (Exception e) {

			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0006);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";

		}
	}

	/**
	 * @author hoangnn
	 * @param context
	 * @param group
	 * @param method
	 * @param paramList
	 * @param timeout
	 * @return
	 */
	public String execGetWithTimeout(Context context, String group,
			String method, List<NameValuePair> paramList) {
		String url = BASE_API_URL + group + '/' + method;
		if (null != paramList) {
			url += getStrParam(paramList);
		}
		HttpClient hClient = new DefaultHttpClient();
		HttpConnectionParams.setSoTimeout(hClient.getParams(), 5000); // Timeout

		try {
			Log.d("URL", "URL REQUEST : " + url);
			HttpGet hget = new HttpGet();
			hget.setURI(new URI(url));
			HttpResponse response = hClient.execute(hget);
			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				String responseString = out.toString();
				Log.d("response", responseString);
				return responseString;
			} else {

				return null;
			}
		} catch (ClientProtocolException e) {

			e.printStackTrace();
			return null;

		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Post method
	 * 
	 * @param group
	 *            : Server API Group đang sử dụng (A,F,L...)
	 * 
	 * @param method
	 *            : Method để lấy dữ liệu về hoặc post dữ liệu lên server
	 * 
	 * @param paramList
	 *            : Danh sách các tham số dạng NameValuePair
	 * 
	 * @return JSON
	 */
	public String execPost(Context context, String group, String method,
			List<NameValuePair> paramList) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpclient.getParams(), 10000); // Timeout
																		// connection
		HttpConnectionParams.setSoTimeout(httpclient.getParams(),
				NORMAL_TIMEOUT);
		String url = BASE_API_URL + group + "/" + method;
		HttpPost httppost = new HttpPost(url);
		HttpResponse response = null;
		try {
			httppost.setEntity(new UrlEncodedFormEntity(paramList));
			response = httpclient.execute(httppost);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			response.getEntity().writeTo(byteArrayOutputStream);
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				String ret = byteArrayOutputStream.toString();
				return ret;
			} else {
				String mess = "";
				mess = mContext.getResources().getString(R.string.ERR0006);
				if (!isShowingDialog) {
					isShowingDialog = true;
					showMessage(mess);
				}
				return "";
			}

		} catch (ConnectTimeoutException e) {
			Log.e("ApiConnectexecPost", e.getMessage());
			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0007);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";
		} catch (Exception e) {
			// TODO: handle exception
			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0006);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return "";
		}
	}

	public String execPostImg(Context context, String group, String method,
			MultipartEntity mulEntity) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpConnectionParams
				.setConnectionTimeout(httpclient.getParams(), 10000); // Timeout
		HttpConnectionParams.setSoTimeout(httpclient.getParams(),
				POST_IMAGE_TIMEOUT);
		String url = BASE_API_URL + group + "/" + method;
		Log.d("URL", url);
		HttpPost httppost = new HttpPost(url);
		try {
			httppost.setEntity(mulEntity);
			HttpResponse response = httpclient.execute(httppost);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			response.getEntity().writeTo(byteArrayOutputStream);
			Log.d("URL", "vao signup");
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				String ret = byteArrayOutputStream.toString();
				return ret;
			} else {
				String mess = "";
				mess = mContext.getResources().getString(R.string.ERR0006);
				if (!isShowingDialog) {
					isShowingDialog = true;
					showMessage(mess);
				}
				return "";
			}

		} catch (ConnectTimeoutException e) {

			Log.e("ApiConnectexecGet", e.getMessage());
			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0007);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return null;

		} catch (Exception e) {

			String mess = "";
			mess = mContext.getResources().getString(R.string.ERR0006);
			if (!isShowingDialog) {
				isShowingDialog = true;
				showMessage(mess);
			}
			return null;

		}
	}

	public void showMessage(String mess) {
		Thread uiThread = new HandlerThread("UIHandler");
		uiThread.start();
		uiHandler = new UIHandler(((HandlerThread) uiThread).getLooper());
		handleUIRequest(mess);
	}

	// End For Error Reprort

	public static String exectGet(String strUrl) {
		try {
			URL url = new URL(strUrl);
			HttpURLConnection http;
			http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("GET");
			http.connect();
			InputStream is = http.getInputStream();
			String ret = inputStreem2str(is);
			is.close();

			return ret;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;

	}

	/**
	 * Build URL
	 * 
	 * @param params
	 * 
	 * @return params URL
	 */
	static public String getStrParam(List<NameValuePair> params) {
		String ret = "?";
		boolean flgAdd = false;

		for (int i = 0; params.size() > i; i++) {
			NameValuePair nvp = params.get(i);

			if (flgAdd) {
				ret += "&";
			}

			ret += nvp.getName() + "=" + nvp.getValue();

			flgAdd = true;

		}

		return ret;

	}

	public String buildUrl(String group, String method,
			List<NameValuePair> paramList) {
		String url = BASE_API_URL + group + '/' + method;
		if (null != paramList) {
			url += getStrParam(paramList);
		}
		return url;
	}

	public String buildBaseUrl(String group, String method) {
		String url = BASE_API_URL + group + '/' + method;
		return url;
	}

	// /////////////////////////////////////////USE FOR UPLOAD
	// SERVICE///////////////////////////
	/*
	 * (non-Javadoc)
	 * 
	 * @see me.openphoto.android.app.net.IOpenPhotoApi#uploadPhoto(java.io.File,
	 * me.openphoto.android.app.net.UploadMetaData)
	 */
	public UploadResponse uploadPhoto(File imageFile, UploadMetaData metaData,
			ProgressListener progressListener) throws ClientProtocolException,
			IOException, IllegalStateException, JSONException {
		ApiRequest request = new ApiRequest(ApiRequest.POST,
				"/photo/upload.json");
		request.setMime(true);
		if (metaData.getTags() != null) {
			request.addParameter("tags", metaData.getTags());
		}
		if (metaData.getTitle() != null) {
			request.addParameter("title", metaData.getTitle());
		}
		if (metaData.getDescription() != null) {
			request.addParameter("description", metaData.getDescription());
		}
		request.addParameter("permission",
				Integer.toString(metaData.getPermission()));

		request.addFileParameter("photo", imageFile);
		ApiResponse response = execute(request, progressListener);
		String responseString = response.getContentAsString();
		return new UploadResponse(new JSONObject(responseString));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @binhbt GJ
	 * 
	 * @see me.openphoto.android.app.net.IOpenPhotoApi#uploadPhoto(java.io.File,
	 * me.openphoto.android.app.net.UploadMetaData)
	 */
	public Photo uploadPhotox(File imageFile, JSONObject metaData,
			ProgressListener progressListener) throws ClientProtocolException,
			IOException, IllegalStateException, JSONException {
		ApiRequest request = new ApiRequest(ApiRequest.POST, "Photo/postPhotox");
		request.setMime(true);
		if (metaData.opt("user_id") != null) {
			request.addParameter("user_id", metaData.getString("user_id"));
		}
		if (metaData.opt("button_type") != null) {
			request.addParameter("button_type",
					metaData.getString("button_type"));
		}
		if (metaData.opt("longitude") != null) {
			request.addParameter("longitude", metaData.getString("longitude"));
		}
		if (metaData.opt("latitude") != null) {
			request.addParameter("latitude", metaData.getString("latitude"));
		}
		if (metaData.opt("comment") != null) {
			request.addParameter("comment", metaData.getString("comment"));
		}
		if (metaData.opt("filter_id") != null) {
			request.addParameter("filter_id", metaData.getString("filter_id"));
		}
		if (metaData.opt("location_longitude") != null) {
			request.addParameter("location_longitude",
					metaData.getString("location_longitude"));
		}
		if (metaData.opt("location_latitude") != null) {
			request.addParameter("location_latitude",
					metaData.getString("location_latitude"));
		}
		if (metaData.opt("location_text") != null) {
			request.addParameter("location_text",
					metaData.getString("location_text"));
		}
		if (metaData.opt("model") != null) {
			request.addParameter("model", metaData.getString("model"));
		}
		if (metaData.opt("timezone") != null) {
			request.addParameter("timezone", metaData.getString("timezone"));
		}
		if (metaData.opt("friend") != null) {
			request.addParameter("friend", metaData.getString("friend"));
		}
		if (metaData.opt("list_tags") != null) {
			request.addParameter("list_tags", metaData.getString("list_tags"));
		}
		if (metaData.opt("client_time") != null) {
			request.addParameter("client_time",
					metaData.getString("client_time"));
		}
		if (metaData.opt("isImageAttach") != null) {
			isImageAttach = metaData.getBoolean("isImageAttach");
		}
		request.addFileParameter("photo_object", imageFile);
		ApiResponse response = executex(request, progressListener);
		String responseString = response.getContentAsString();
		Log.d("^^^^^^^^^ upload result", responseString);
		JsonPaser jP = new JsonPaser();
		Photo photo = jP.postPhoto(responseString);
		return photo;
	}

	/**
	 * Execute a request to the API.
	 * 
	 * @param request
	 *            request to perform
	 * @param listener
	 *            Progress Listener with callback on progress
	 * @return the response from the API
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public ApiResponse execute(ApiRequest request, ProgressListener listener)
			throws ClientProtocolException, IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpUriRequest httpRequest = createHttpRequest(request, listener);

		httpRequest.getParams().setBooleanParameter(
				"http.protocol.expect-continue", false);
		// if (mOAuthConsumer != null) {
		// try {
		// mOAuthConsumer.sign(httpRequest);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		return new ApiResponse(httpClient.execute(httpRequest));
	}

	/**
	 * Execute a request to the API.
	 * 
	 * @param request
	 *            request to perform
	 * @param listener
	 *            Progress Listener with callback on progress
	 * @return the response from the API
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public ApiResponse executex(ApiRequest request, ProgressListener listener)
			throws ClientProtocolException, IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(
				CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		HttpUriRequest httpRequest = createHttpRequestx(request, listener);

		httpRequest.getParams().setBooleanParameter(
				"http.protocol.expect-continue", false);
		return new ApiResponse(httpClient.execute(httpRequest));
	}

	/**
	 * Create a HttpUriRequest out of a ApiRequest object.
	 * 
	 * @param request
	 *            the ApiRequest for which a HttpUriRequest should be created
	 * @param listener
	 *            Progress Listener with callback on progress
	 * @return HttpUriRequest object which will do the request as described in
	 *         ApiRequest
	 * @throws UnsupportedEncodingException
	 */
	private HttpUriRequest createHttpRequest(ApiRequest request,
			ProgressListener listener) throws UnsupportedEncodingException {
		HttpUriRequest httpRequest = null;
		switch (request.getMethod()) {
		case ApiRequest.GET:
			httpRequest = new HttpGet(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		case ApiRequest.POST:
			httpRequest = new HttpPost(BASE_API_URL + request.getPath());
			HttpPost httpPost = ((HttpPost) httpRequest);
			if (request.isMime()) {
				// TODO use the multipart when possible (currently server
				// handles it wrong)
				// HttpEntity entity = createMultipartEntity(request);
				// TODO remove this when doing correct multipart
				httpRequest = new HttpPost(addParamsToUrl(BASE_API_URL
						+ request.getPath(), request.getParameters()));
				httpPost = ((HttpPost) httpRequest);
				HttpEntity entity = createFileOnlyMultipartEntity(request);
				if (listener != null) {
					httpPost.setEntity(new HttpEntityWithProgress(entity,
							listener));
				} else {
					httpPost.setEntity(entity);
				}
			} else {
				httpPost.setEntity(new UrlEncodedFormEntity(request
						.getParameters(), HTTP.UTF_8));
			}
			break;
		case ApiRequest.PUT:
			httpRequest = new HttpPut(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		case ApiRequest.DELETE:
			httpRequest = new HttpDelete(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		}

		for (NameValuePair pair : request.getHeaders()) {
			request.addHeader(pair.getName(), pair.getValue());
		}

		return httpRequest;
	}

	/**
	 * Create a HttpUriRequest out of a ApiRequest object.
	 * 
	 * @param request
	 *            the ApiRequest for which a HttpUriRequest should be created
	 * @param listener
	 *            Progress Listener with callback on progress
	 * @return HttpUriRequest object which will do the request as described in
	 *         ApiRequest
	 * @throws UnsupportedEncodingException
	 */
	private HttpUriRequest createHttpRequestx(ApiRequest request,
			ProgressListener listener) throws UnsupportedEncodingException {
		HttpUriRequest httpRequest = null;
		switch (request.getMethod()) {
		case ApiRequest.GET:
			httpRequest = new HttpGet(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		case ApiRequest.POST:
			httpRequest = new HttpPost(BASE_API_URL + request.getPath());
			HttpPost httpPost = ((HttpPost) httpRequest);
			if (request.isMime()) {
				// TODO use the multipart when possible (currently server
				// handles it wrong)
				// HttpEntity entity = createMultipartEntity(request);
				// TODO remove this when doing correct multipart
				httpRequest = new HttpPost(addParamsToUrl(BASE_API_URL
						+ request.getPath(), request.getParameters()));
				httpPost = ((HttpPost) httpRequest);
				if (isImageAttach == Constant.ON) {
					HttpEntity entity = createFileOnlyMultipartEntityx(request);
					if (listener != null) {
						httpPost.setEntity(new HttpEntityWithProgress(entity,
								listener));
					} else {
						httpPost.setEntity(entity);
					}
				}
			} else {
				httpPost.setEntity(new UrlEncodedFormEntity(request
						.getParameters(), HTTP.UTF_8));
			}
			break;
		case ApiRequest.PUT:
			httpRequest = new HttpPut(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		case ApiRequest.DELETE:
			httpRequest = new HttpDelete(addParamsToUrl(
					BASE_API_URL + request.getPath(), request.getParameters()));
			break;
		}

		for (NameValuePair pair : request.getHeaders()) {
			request.addHeader(pair.getName(), pair.getValue());
		}

		return httpRequest;
	}

	private HttpEntity createFileOnlyMultipartEntity(ApiRequest request)
			throws UnsupportedEncodingException {
		MultipartEntity entity = new MultipartEntity();
		for (Parameter<?> parameter : request.getParametersMime()) {
			if (parameter.getValue() instanceof File) {
				File file = (File) parameter.getValue();
				entity.addPart(parameter.getName(), new FileBody(file));
			}
		}
		return entity;
	}

	private HttpEntity createFileOnlyMultipartEntityx(ApiRequest request)
			throws UnsupportedEncodingException {
		MultipartEntity entity = new MultipartEntity();
		for (Parameter<?> parameter : request.getParametersMime()) {
			if (parameter.getValue() instanceof File) {
				File file = (File) parameter.getValue();
				// For compress file before upload
				Bitmap bitmap = BitmapFactory
						.decodeFile(file.getAbsolutePath());
				int quality = 50;
				try {
					long realSize = file.length();
					quality = (int) (5 * Constant.X_SIZE / realSize);
					quality = quality > 90 ? 90 : quality;
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bitmap.compress(CompressFormat.JPEG, quality, bos);
				// Log.d("<<<< bitmap size pure",
				// "..."+getImageLength(selectedImagePath));
				Log.d("<<<< bitmap size",
						"quality " + quality + "..." + bos.size());
				byte[] data = bos.toByteArray();
				ByteArrayBody bad = new ByteArrayBody(data, "");
				entity.addPart(parameter.getName(), bad);
				// entity.addPart(parameter.getName(), new FileBody(file));
			}
		}
		return entity;
	}

	@SuppressWarnings("unused")
	private MultipartEntity createMultipartEntity(ApiRequest request)
			throws UnsupportedEncodingException {
		Charset stringCharset = Charset.forName("UTF-8");
		MultipartEntity entity = new MultipartEntity();
		for (Parameter<?> parameter : request.getParametersMime()) {
			if (parameter.getValue() instanceof String) {
				entity.addPart(parameter.getName(), new StringBody(
						(String) parameter.getValue(), stringCharset));
			} else if (parameter.getValue() instanceof File) {
				File file = (File) parameter.getValue();
				entity.addPart(parameter.getName(), new FileBody(file));
			}
		}
		return entity;
	}

	/**
	 * Adds the parameters to the given url.
	 * 
	 * @param url
	 *            the url
	 * @param nameValuePairs
	 *            the name value pairs to be added to the url
	 * @return the url with added parameters
	 */
	private String addParamsToUrl(String url, List<NameValuePair> nameValuePairs) {
		if (nameValuePairs == null || nameValuePairs.isEmpty()) {
			return url;
		}

		final StringBuffer newUrl = new StringBuffer(url);
		newUrl.append(url.contains("?") ? '&' : '?');

		for (NameValuePair param : nameValuePairs) {
			newUrl.append(param.getName() + "="
					+ URLEncoder.encode(param.getValue()) + "&");
		}
		newUrl.deleteCharAt(newUrl.length() - 1);
		return newUrl.toString();
	}

	/**
	 * share to social network
	 */
	public void shareToSocialNetWork(JSONObject data) {
		try {
			User mUser = UserUtil.getInfoUserLogin(mContext);

			DatabaseHelper mDb = new DatabaseHelper(mContext);
			Log.d("P06", "Post social network!");
			String imagePath = data.getString("imagePath");
			String url_id = data.getString("url_id");
			if (imagePath == null || !isImageAttach) {
				imagePath = Constant.XCOMIC_ICON_ASSET;
			}
			Log.d("P06", "Image Path: " + imagePath);
			SocialUntil social = new SocialUntil(mContext);
			boolean result = false;
			try {
				if (data.getBoolean("isFacebook") == Constant.ON) {
					FacebookUser fbUser = mDb.getFacebookUser(mUser
							.getUser_id());
					Log.d("P06", "facebook");
					String accessToken = fbUser.getAccessToken();
					Log.d("P06", "facebook access: " + accessToken
							+ ", message: " + data.getString("facebookMessage"));
					// checkins
					if (data.opt("place_name") != null) {
						result = social.checkInToFacebook(
								data.getString("photo_url"),
								data.getString("facebookMessage").replaceAll(
										Constant.URL_PHOTO_ID_EMPTY, url_id),
								accessToken, new Place(),
								data.getString("listFriendID"), url_id);
					} else {
						result = social.postToFacebook(
								imagePath,
								data.getString("facebookMessage").replaceAll(
										Constant.URL_PHOTO_ID_EMPTY, url_id),
								accessToken);
					}
					Log.v("P06", "Post to facebook: " + result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			// Post to tumblr
			try {
				if (data.getBoolean("isTumblr") == Constant.ON) {
					TumblrUser tumUser = mDb.getTumblrUser(mUser.getUser_id());
					String email = tumUser.getUsername();
					String password = tumUser.getPassword();
					Log.d("P06", "tumblr email: " + email + ", message: "
							+ data.getString("tumblrMessage"));
					result = social.postToTumblr(
							imagePath,
							data.getString("tumblrMessage").replaceAll(
									Constant.URL_PHOTO_ID_EMPTY, url_id),
							email, password);
					Log.v("P06", "Post to Tumblr: " + result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			// Twitter
			try {
				if (data.getBoolean("isTwitter") == Constant.ON) {
					TwitterUser twiUser = mDb
							.getTwitterUser(mUser.getUser_id());
					String token = twiUser.getTwitterToken();
					String secret = twiUser.getTwitterSecret();
					Log.v("P06", "twitter token: " + token);
					Log.d("P06",
							" twitter message: "
									+ data.getString("twitterMessage"));
					result = social.postToTwitter(
							imagePath,
							data.getString("twitterMessage").replaceAll(
									Constant.URL_PHOTO_ID_EMPTY, url_id),
							token, secret);
					Log.v("P06", "post to Twitter: " + result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			// flickr
			try {
				if (data.getBoolean("isFlickr") == Constant.ON) {
					FlickrUser flUser = mDb.getFlickrUser(mUser.getUser_id());
					String token = flUser.getAccessToken();
					result = social.postToFlickr(
							imagePath,
							data.getString("flickrMessage").replaceAll(
									Constant.URL_PHOTO_ID_EMPTY, url_id),
							url_id, token);
					Log.v("P06", "post to Flickr: " + result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			// Post to weibo.
			try {
				if (data.getBoolean("isWeibo") == Constant.ON) {
					// Log.d("P06", "weibo link: " +
					// mDb.isWeiboLinked(mUser.getUser_id()));
					WeiboUser weiUser = mDb.getWeiboUser(mUser.getUser_id());
					String token = weiUser.getWeiboToken();
					String secret = weiUser.getWeiboSecret();
					result = social.postToWeibo(
							imagePath,
							data.getString("weiboMessage").replaceAll(
									Constant.URL_PHOTO_ID_EMPTY, url_id), "",
							"", token, secret);
					Log.v("P06", "post to Weibo: " + result);
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}
